// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let data = null
  let address = {
    _id: event._id,
    city: event.city,
    country: event.country,
    detail: event.detail,
    name: event.name,
    primary: event.primary,
    province: event.province,
    tag: event.tag,
    telnum: event.telnum,
    user_openid: wxContext.OPENID
  }

  if(event.status == 0){
    address['status'] = 0
  }

  if (event.primary == 1) {
    await db.collection('SJBL_Address').where({
      primary: 1
    }).update({
      data: {
        primary: 0
      }
    })
  }

  if (event.flag == 'add') {
    if (address._id !== undefined) delete address._id;
    address['create_time'] = new Date()
    address['user_openid'] = wxContext.OPENID
    address['status'] = 1

    data = await db.collection('SJBL_Address').add({
      data: address
    })
  } else {
    if (address._id !== undefined) delete address._id;
    data = await db.collection('SJBL_Address').where({
      _id: event._id
    }).update({
      data: address
    })
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    data
  }
}